<?php
require_once dirname(__FILE__) . '/../incls/php/dbutils.class.php';
require_once dirname(__FILE__) . '/../incls/php/miscutils.class.php';

if (isset($_FILES['Filedata']) && is_uploaded_file($_FILES['Filedata']['tmp_name']) && $_FILES['Filedata']['error'] == 0) {
  //获得上传文件信息
  $upload_file = $_FILES['Filedata'];
  //获取文件扩展名
  $file_info = pathinfo($upload_file['name']);
  $file_ext = (isset($file_info['extension'])) ? $file_info['extension'] : '';
  
  //获取客户端参数
  $action = $_POST['action'];
  
  //Add custom code here...
  $updir = "../exts/$action/" . $file_info['filename'];
  $result = new stdClass();
  if (file_exists($updir)) {
    unlink($upload_file['tmp_name']);
    $result->msg = 'File already exists';
    echo json_encode($result);
    return;
  }
  
  create($updir);
  
  $zip = new ZipArchive;
  if ($zip->open($upload_file['tmp_name']) === TRUE) {
    $myPdo = DbUtils::createPdoInst();
    $zip->extractTo($updir);
    $zip->close();
    $infile = "../exts/$action/" . $file_info['filename'] . '/install.php';
    if (file_exists($infile)) {
      require_once $infile;
      $result->msg = 'Installed';
    } else {
      MiscUtils::rrmdir($updir);
      $result->msg =  'Can\'t install';
    }
  } else {
    $result->msg =  'Can\'t extract file';
  }
  echo json_encode($result);
  unlink($upload_file['tmp_name']);
}

//若没有这个文件夹，则需要创建文件夹
function create($dir) {
  if (!is_dir($dir)) {
    $temp = explode('/',$dir);
    $cur_dir = '';
    for($i = 0; $i < count($temp); $i++) {
      $cur_dir .= $temp[$i].'/';
      if (!is_dir($cur_dir)) {
        @mkdir($cur_dir, 0777);
      }
    }
  }
}
?>